package algorithm.leetcode.simple;

/*
 罗马数字转整数
 */

import java.util.HashMap;
import java.util.Map;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020/8/19
 */
public class Question13 {

    public static void main(String[] args) {
        Question13 question = new Question13();
        int toInt = question.romanToInt("MCMXCIV");
        System.out.println(toInt);
    }

    public int romanToInt(String s) {
        Map<Character, Integer> map = new HashMap<>(16);
        map.put('M', 1000);
        map.put('D', 500);
        map.put('C', 100);
        map.put('L', 50);
        map.put('X', 10);
        map.put('V', 5);
        map.put('I', 1);
        int result = 0;
        Integer num = map.get(s.charAt(0));
        // MCMXCIV 1000 + 900 + 90 + 4
        for (int i = 1; i < s.length(); i++) {
            Integer num1 = map.get(s.charAt(i));
            if (num < num1) {
                result -= num;
            } else {
                result += num;
            }
            num = num1;
        }
        result += num;
        return result;
    }

}
